package com.fbinggun.sql;

import org.bukkit.plugin.Plugin;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 数据库父类(DB数据库) 请使用SqlUtil类创建
 */
public class SQLite {

    private Plugin plugin;
    private Connection connection;
    //数据库
    private Statement statement;
    private  String dbFilePath;


    public SQLite(Plugin plugin, String dbFilePath) throws SQLException, ClassNotFoundException {
        this.plugin = plugin;
        this.dbFilePath = plugin.getDataFolder().getPath()+"/"+dbFilePath;
        this.connection=getConnections();
        this.statement=connection();
    }

    public SQLite(String dbFilePath) throws SQLException, ClassNotFoundException {
        this.dbFilePath = dbFilePath;
        this.connection=getConnections();
        this.statement=connection();
    }

    public SQLite(Plugin plugin) {
        this.plugin = plugin;
    }
    public SQLite() {

    }
    public Connection getConnections() throws SQLException, ClassNotFoundException {
        // 1、加载驱动
        Class.forName("org.sqlite.JDBC");
        // 2、建立连接
        // 注意：此处有巨坑，如果后面的 dbFilePath 路径太深或者名称太长，则建立连接会失败
        connection = DriverManager.getConnection("jdbc:sqlite:" + dbFilePath);
        return connection;
    }


    //关闭此数据库连接
    public void CloseSql() throws SQLException {
        statement.close();
        connection.close();

    }
    //连接数据库
    public Statement connection() throws SQLException, ClassNotFoundException {
      if(connection==null){
          getConnections();
      }
        this.statement = connection.createStatement();
        return statement;
    }
    //判断数据库是否是链接状态
    public boolean IsConnection() throws SQLException {
        return statement.isClosed();
    }

    public Connection getConnection() throws SQLException, ClassNotFoundException {
        return connection;
    }

    public Statement getStatement() throws SQLException {
        return connection.createStatement();
    }

}
